package cz.semjobKB.invoke_treex.service;

import cz.semjobKB.invoke_treex.api.ITreexService;
import cz.semjobKB.treex.service.api.IRemoteNlp;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;


@Service
public class TreexService implements ITreexService {

	private static Logger logger = Logger.getLogger(TreexService.class);
		
	IRemoteNlp remoteNlp;

    /**
     * Cosntructor
     */
	public TreexService() {
		@SuppressWarnings("resource")
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-config-client.xml");
		remoteNlp = (IRemoteNlp)context.getBean("remoteNlp");
	}
	
	
	public File invokeLinguisticPocessing (String fileName) {
		logger.info("Invoking Treex");
		File origFile = new File(fileName);
		if(!origFile.exists()) {
			return null;
		}
		logger.info("Start processing file: " + origFile.getName());
		
		File outputFile = loadAllreadyProcessedFile(origFile);
		
		if (outputFile.exists()) {
			String outputText;
			try {
				outputText = FileUtils.readFileToString(outputFile);
				if (outputText != null && !outputText.isEmpty()) {
					return outputFile;
				}	
			} catch (IOException e) {				
			}
						
		}
		String textToProcess = "";
		try {
			textToProcess = FileUtils.readFileToString(origFile);
		} catch (IOException e) {
			return null;
		}
		
		String output = remoteNlp.remoteNlp(textToProcess);
		
		try {
            if (output != null) {
			    FileUtils.writeStringToFile(outputFile, output);
            }
		} catch (IOException e) {
			return null;
		}
        		
		return outputFile;
	}

    /*Gets the file that was already processed
     */
	private File loadAllreadyProcessedFile (File fileToProcess) {
		 
		 String outputName = FilenameUtils.removeExtension(fileToProcess.getName()) + ".conll";    
    	 String outputFilePath = new File(fileToProcess.getParent()).getParent() + File.separator + 
    			 "linguistic" + File.separator + outputName;
    	 outputFilePath = outputFilePath.replaceAll(" ", "_");
    	 File outputFile = new File(outputFilePath);		 
         return outputFile;
	}	
	
}
